package br.com.dataphonebr;


import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import br.com.dataphonebr.exception.CredentialsException;
import br.com.dataphonebr.schedule.SampleAlarmReceiver;
import br.com.dataphonebr.service.CredentialsService;
import br.com.dataphonebr.util.Util;

public class MainActivity extends Activity {

	private EditText userEdit;
	private EditText passwordEdit;
	private CheckBox userConnectedChk;
	private CredentialsService credentialsService;
	private SharedPreferences preferences;
	protected Util util = new Util();
	private SampleAlarmReceiver alarm = new SampleAlarmReceiver();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		credentialsService = new CredentialsService(this, this);
		userEdit = (EditText) findViewById(R.id.user);
		passwordEdit = (EditText) findViewById(R.id.password);
		userConnectedChk = (CheckBox) findViewById(R.id.manterConectado);
		DatabaseManager.initializeInstance(new DataphoneHelper(this));
		if (credentialsService.noUsers()){
	    	startActivity(new Intent(MainActivity.this, DashboardActivity.class));
	    	finish();
		} else {
			userEdit.setText(credentialsService.getUniqueUser().getLogin());
		}
	}
	
	@Override
	protected void onResume() {
		boolean alarmPrefs = preferences.getBoolean(SettingsActivity.ATIVAR_ALARME, false);
		boolean connected = preferences.getBoolean(SettingsActivity.MANTER_CONECTADO, false);
		if (connected){
			if (credentialsService.resumeLogin()){
				if (!alarmPrefs)
					alarm.cancelAlarm(this);
		    	startActivity(new Intent(MainActivity.this, DashboardActivity.class));
		    	finish();
			}
		}
		super.onResume();
   }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
    public void loginOnClick(View v) throws CredentialsException {
		String user = userEdit.getText().toString().toLowerCase(new Locale("pt", "BR")).trim();
		String password = passwordEdit.getText().toString().trim();

		if (user.equals("") && password.equals("")){
			util.showToastMessage(R.string.msg_autentication_error, this);
			return;
		} 
		
		try {
			credentialsService.login(user, password);
			Editor editor = preferences.edit();
			editor.putBoolean(SettingsActivity.MANTER_CONECTADO, userConnectedChk.isChecked());
			editor.commit();
			startActivity(new Intent(MainActivity.this, DashboardActivity.class));
			finish();
		} catch (CredentialsException e){
			util.showToastMessageLong(e.getMessage(), this);
			e.printStackTrace();
		}
    }
    
    public void forgotMyPasswordOnClick(View v) throws CredentialsException {
    	final Context context = this;
    	DialogInterface.OnClickListener clickOk = new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface arg0, int arg1) {
    			String message = getString(R.string.msg_email_sent_successfully);
    			String user = userEdit.getText().toString().toLowerCase().trim();
    			try {
    				credentialsService.sendForgotMyPassword(user);
    			} catch (RuntimeException e){
    				message = e.getMessage();
	    			e.printStackTrace();
    			} catch (CredentialsException e){
    				message = e.getMessage();
    				e.printStackTrace();
    			} finally {
    				util.showToastMessageLong(message, context);
    			}
    		}
    	};
    	
    	DialogInterface.OnClickListener clickCancel = new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface arg0, int arg1) {
    			arg0.dismiss();
    		}
    	};
    	
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setPositiveButton(getString(R.string.send_label), clickOk);
		builder.setNegativeButton(getString(R.string.cancel), clickCancel);
		builder.setMessage(getString(R.string.msg_send_forgot_my_password));
		builder.create();
		builder.show();
    }
    
}
